package highlight_spring4;

import highlight_spring4.interceptor.DemoInterceptor;
import highlight_spring4.messageconverter.MyMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import java.util.List;

@Configuration
//@EnableWebMvc开启SpringMVC支持，若无此句，重写WebMvcConfigurerAdapter方法无效。
@EnableWebMvc
@ComponentScan("highlight_spring4")
//继承WebMvcConfigurerAdapter类，重写其方法可对SpringMVC进行配置。
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;

    }
//    @Override
//    public void addResourceHandlers(ResourceHandlerRegistry registry){
//        //addResourceLocations指的是文件放置的目录，addResourceHandler指的是对外暴露的访问路径。
//        registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
//        super.addResourceHandlers(registry);
//
//        //registry.addResourceHandler("/assets/js/*").addResourceLocations("classpath:/assets/js/*");
//    }
    //配置拦截器的Bean
    @Bean
    public DemoInterceptor demoInterceptor(){
        return new DemoInterceptor();
    }

    @Override
    //重写addInterceptors方法，注册拦截器
    public  void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(demoInterceptor());
    }
    @Override
    public void addViewControllers(ViewControllerRegistry registry){
        registry.addViewController("index").setViewName("index");
        registry.addViewController("toUpload").setViewName("upload");
        registry.addViewController("converter").setViewName("conventer");
    }
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer){
        configurer.setUseSuffixPatternMatch(false);
    }
    //MultipartResolve配置。
    @Bean
    public MultipartResolver multipartResolver(){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(1000000);
        return multipartResolver;
    }
    @Bean
    public MyMessageConverter converter(){
        return new MyMessageConverter();
    }
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters){
        converters.add(converter());

    }
}
